import { getPatientBaseObject } from '../../../utils/api/patientBase';
import { 
  getLatestBloodOxygen, 
  getBloodOxygenPage, 
  getBloodOxygenByDate,
  getBloodOxygenCount,
  getAvgBloodOxygen 
} from '../../../utils/api/bloodOxygen';
import {
  getLatestStepCount,
  getStepCountPage,
  getStepCountByDate,
  getAllStepCount
} from '../../../utils/api/stepCount';

Page({
  data: {
    userInfo: {
      avatarUrl: '',
      displayName: '用户',
      patientName: '',
      patientUid: '1' // 这里应该从用户信息中获取，暂时写死
    },
    totalStepsText: '--',
    oxygenDetailRangeText: '--',
    averageOxygenText: '--',
    lowOxygenAlertText: '--',
    chartTimeType: 'week',
    chartDateRange: '--',
    currentDate: new Date(),
    selectedDate: '', // YYYY-MM-DD
    showCalendar: false,
    calendarType: 'single', // 'single' | 'range'
    calendarMinDate: null, // 日历最小日期（三个月前）
    calendarMaxDate: null, // 日历最大日期（今天）
    weekStartDate: null,
    weekEndDate: null,
    monthsAgo: 0, // 用于月份导航
    currentMonth: new Date(), // 当前选择的月份
    chartData: {
      categories: [],
      series: [
        { name: '步数', data: [], color: '#52C41A', type: 'bar' }
      ]
    },
    sectionTitle: '本周步数基本情况',
    isLoading: true,
    
    // 步数目标相关
    currentSteps: 0, // 当前步数
    goalSteps: 10000, // 目标步数
    progressPercent: 0, // 进度百分比
    remainingSteps: 0, // 剩余步数
    caloriesBurned: 0, // 消耗卡路里
    distanceKm: 0, // 距离（公里）
    eggsCount: 0, // 相当于几个鸡蛋
    lapsCount: 0 // 相当于几圈操场
  },

  async onLoad() {
    try {
      await this.getUserInfo();
      const today = new Date();
      // 初始化周的起止日期（默认视图是周）
      const { start, end } = this.getWeekRange(today);
      
      // 计算日历日期范围（最近三个月）
      const maxDate = new Date();
      const minDate = new Date();
      minDate.setMonth(minDate.getMonth() - 3);
      
      this.setData({
        selectedDate: this.formatDateYMD(today),
        currentDate: today,
        currentMonth: today,
        weekStartDate: start,
        weekEndDate: end,
        chartDateRange: this.formatDateRangeDisplay(start, end),
        calendarMinDate: minDate.getTime(),
        calendarMaxDate: maxDate.getTime()
      });
      // 初始化目标进度（显示初始值）
      this.calculateGoalProgress();
      // 加载数据
      this.loadData();
    } catch (error) {
      console.error('页面加载失败:', error);
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
    }
  },

  onPullDownRefresh() {
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 600);
  },

  // 加载数据
  async loadData() {
    try {
      this.setData({ isLoading: true });
      await this.loadStatistics();
      await this.loadChartData();
    } catch (error) {
      console.error('加载数据失败:', error);
      wx.showToast({
        title: '加载数据失败',
        icon: 'none'
      });
    } finally {
      this.setData({ isLoading: false });
    }
  },
  
  // 加载统计数据（步数和血氧）
  async loadStatistics() {
    const patientUid = this.data.userInfo && this.data.userInfo.patientUid;
    if (!patientUid) {
      console.warn('patientUid缺失，跳过统计数据加载');
      return;
    }
    
    try {
      const { chartTimeType, selectedDate, weekStartDate, weekEndDate, currentMonth } = this.data;
      
      // 加载步数数据
      let stepRecords = [];
      
      if (chartTimeType === 'day') {
        // 获取当天的步数数据
        console.log(`准备调用步数API - 日期: ${selectedDate}, patientUid: ${patientUid}`);
        const res = await getStepCountByDate(patientUid, { date: selectedDate });
        console.log(`日视图 ${selectedDate} 的步数API完整响应:`, JSON.stringify(res));
        // 处理各种响应格式
        if (Array.isArray(res)) {
          stepRecords = res;
        } else if (res && res.records) {
          stepRecords = res.records;
        } else if (res && res.data) {
          stepRecords = Array.isArray(res.data) ? res.data : (res.data.records || []);
        } else {
          stepRecords = [];
        }
        console.log(`日视图 ${selectedDate} 筛选后步数记录数:`, stepRecords.length);
      } else if (chartTimeType === 'week') {
        // 获取一周的步数数据
        const res = await getStepCountPage(patientUid, { 
          pageNum: 1, 
          pageSize: 100,
          sortField: 'uploadTime',
          sortOrder: 'desc'
        });
        const allRecords = res.records || res.data?.records || [];
        
        // 筛选出本周的数据
        const weekStart = weekStartDate || this.getWeekRange(new Date()).start;
        const startTime = this.formatDateYMD(weekStart);
        const endDate = new Date(weekStart);
        endDate.setDate(endDate.getDate() + 6);
        const endTime = this.formatDateYMD(endDate);
        
        stepRecords = allRecords.filter(item => {
          if (item && item.uploadTime) {
            const date = item.uploadTime.split('T')[0];
            return date >= startTime && date <= endTime;
          }
          return false;
        });
      } else if (chartTimeType === 'month') {
        // 获取一个月的步数数据
        const res = await getStepCountPage(patientUid, { 
          pageNum: 1, 
          pageSize: 100,
          sortField: 'uploadTime',
          sortOrder: 'desc'
        });
        const allRecords = res.records || res.data?.records || [];
        
        // 筛选出当前月份的数据
        const targetMonth = currentMonth || new Date();
        const targetYear = targetMonth.getFullYear();
        const targetMonthNum = targetMonth.getMonth();
        
        stepRecords = allRecords.filter(item => {
          if (item && item.uploadTime) {
            const date = new Date(item.uploadTime);
            return date.getFullYear() === targetYear && date.getMonth() === targetMonthNum;
          }
          return false;
        });
      }
      
      console.log(`${chartTimeType}步数统计数据，筛选后记录数:`, stepRecords.length);
      
      // 计算步数统计数据
      if (Array.isArray(stepRecords) && stepRecords.length > 0) {
        // 提取步数值
        const stepValues = stepRecords
          .map(item => item && item.steps)
          .filter(val => val !== undefined && val !== null && typeof val === 'number');
        
        if (stepValues.length > 0) {
          // 计算总步数
          const totalSteps = stepValues.reduce((sum, val) => sum + val, 0);
          
          // 更新步数和目标相关数据
          this.setData({
            totalStepsText: `${totalSteps}步`,
            currentSteps: totalSteps
          }, () => {
            this.calculateGoalProgress();
          });
          
          console.log('步数统计数据已更新:', { 
            时间类型: chartTimeType,
            总步数: `${totalSteps}步`,
            数据条数: stepValues.length
          });
        } else {
          // 有记录但没有有效的步数值
          this.setData({
            totalStepsText: '--'
          });
          console.log('当前时间范围内无有效步数数据');
        }
      } else {
        // 没有数据时显示默认值
        this.setData({
          totalStepsText: '--'
        });
        console.log(`${chartTimeType}视图 - 当前时间范围内无步数数据`);
      }
      
      // 加载血氧数据（用于血氧范围、平均血氧、偏低提醒）
      let oxygenRecords = [];
      if (chartTimeType === 'day') {
        const res = await getBloodOxygenByDate(patientUid, { date: selectedDate });
        oxygenRecords = Array.isArray(res) ? res : (res.records || res.data?.records || res.data || []);
      } else if (chartTimeType === 'week') {
        const res = await getBloodOxygenPage(patientUid, { pageNum: 1, pageSize: 100, sortField: 'uploadTime', sortOrder: 'desc' });
        const allRecords = res.records || res.data?.records || [];
        const weekStart = weekStartDate || this.getWeekRange(new Date()).start;
        const startTime = this.formatDateYMD(weekStart);
        const endDate = new Date(weekStart);
        endDate.setDate(endDate.getDate() + 6);
        const endTime = this.formatDateYMD(endDate);
        oxygenRecords = allRecords.filter(item => {
          if (item && item.uploadTime) {
            const date = item.uploadTime.split('T')[0];
            return date >= startTime && date <= endTime;
          }
          return false;
        });
      } else if (chartTimeType === 'month') {
        const res = await getBloodOxygenPage(patientUid, { pageNum: 1, pageSize: 100, sortField: 'uploadTime', sortOrder: 'desc' });
        const allRecords = res.records || res.data?.records || [];
        const targetMonth = currentMonth || new Date();
        const targetYear = targetMonth.getFullYear();
        const targetMonthNum = targetMonth.getMonth();
        oxygenRecords = allRecords.filter(item => {
          if (item && item.uploadTime) {
            const date = new Date(item.uploadTime);
            return date.getFullYear() === targetYear && date.getMonth() === targetMonthNum;
          }
          return false;
        });
      }
      
      // 计算血氧统计数据
      if (Array.isArray(oxygenRecords) && oxygenRecords.length > 0) {
        const spo2Values = oxygenRecords
          .map(item => item && item.spo2)
          .filter(val => val !== undefined && val !== null && typeof val === 'number');
        
        if (spo2Values.length > 0) {
          const maxSpo2 = Math.max(...spo2Values);
          const minSpo2 = Math.min(...spo2Values);
          const avgSpo2 = Math.round(spo2Values.reduce((sum, val) => sum + val, 0) / spo2Values.length);
          const lowCount = spo2Values.filter(val => val < 95).length;
          
          this.setData({
            oxygenDetailRangeText: `${minSpo2}-${maxSpo2}%`,
            averageOxygenText: `${avgSpo2}%`,
            lowOxygenAlertText: `${lowCount}次`
          });
        } else {
          this.setData({
            oxygenDetailRangeText: '--',
            averageOxygenText: '--',
            lowOxygenAlertText: '0次'
          });
        }
      } else {
        this.setData({
          oxygenDetailRangeText: '--',
          averageOxygenText: '--',
          lowOxygenAlertText: '0次'
        });
      }
    } catch (error) {
      console.error('加载统计数据失败:', error);
      this.setData({
        totalStepsText: '--',
        oxygenDetailRangeText: '--',
        averageOxygenText: '--',
        lowOxygenAlertText: '0次'
      });
    }
  },
  
  // 加载图表数据
  async loadChartData() {
    try {
      const { chartTimeType, selectedDate, weekStartDate, weekEndDate, currentMonth } = this.data;
      const patientUid = this.data.userInfo && this.data.userInfo.patientUid;
      if (!patientUid) {
        console.warn('patientUid缺失，跳过图表数据加载');
        return;
      }
      let chartData = { categories: [], series: [{ name: '步数', data: [], color: '#52C41A', type: 'bar' }] };
      
      if (chartTimeType === 'day') {
        // 获取当天的步数数据
        const res = await getStepCountByDate(patientUid, { date: selectedDate });
        console.log('日步数图表数据响应:', res);
        
        // 响应拦截器已经提取了数据
        const dataArray = res.records || res.data?.records || res.data || res || [];
        if (Array.isArray(dataArray) && dataArray.length > 0) {
          // 按小时分组
          const hourlyData = new Array(24).fill(null);
          dataArray.forEach(item => {
            if (item && item.uploadTime) {
              const hour = new Date(item.uploadTime).getHours();
              if (hourlyData[hour] === null || item.uploadTime > hourlyData[hour].uploadTime) {
                hourlyData[hour] = item;
              }
            }
          });
          
          chartData.categories = Array.from({ length: 24 }, (_, i) => `${i}时`);
          chartData.series[0].data = hourlyData.map(item => item ? item.steps : null);
          console.log('日步数图表数据已设置');
        } else {
          console.warn('日步数图表无数据');
        }
      } else if (chartTimeType === 'week') {
        // 获取一周的步数数据
        const res = await getStepCountPage(patientUid, { 
          pageNum: 1, 
          pageSize: 100,
          sortField: 'uploadTime',
          sortOrder: 'desc'
        });
        console.log('周步数图表数据响应:', res);
        
        // 响应拦截器已经提取了数据
        const records = res.records || res.data?.records || [];
        if (Array.isArray(records) && records.length > 0) {
          // 获取当前周的7天日期
          const weekStart = weekStartDate || this.getWeekRange(new Date()).start;
          const dates = [];
          for (let i = 0; i < 7; i++) {
            const date = new Date(weekStart);
            date.setDate(weekStart.getDate() + i);
            dates.push(this.formatDateYMD(date));
          }
          
          // 按日期分组，取每天最新的数据
          const dailyData = {};
          records.forEach(item => {
            if (item && item.uploadTime) {
              const date = item.uploadTime.split('T')[0];
              if (dates.includes(date) && (!dailyData[date] || item.uploadTime > dailyData[date].uploadTime)) {
                dailyData[date] = item;
              }
            }
          });
          
          chartData.categories = dates.map(date => {
            const d = new Date(date);
            return `${String(d.getMonth() + 1).padStart(2, '0')}/${String(d.getDate()).padStart(2, '0')}`;
          });
          chartData.series[0].data = dates.map(date => dailyData[date] ? dailyData[date].steps : null);
          console.log('周步数图表数据已设置');
        } else {
          console.warn('周步数图表无数据');
        }
      } else if (chartTimeType === 'month') {
        // 获取一个月的步数数据（显示每天的数据点）
        const res = await getStepCountPage(patientUid, { 
          pageNum: 1, 
          pageSize: 100,
          sortField: 'uploadTime',
          sortOrder: 'desc'
        });
        console.log('月步数图表数据响应:', res);
        
        const allRecords = res.records || res.data?.records || [];
        console.log('提取的步数records:', allRecords.length);
        
        if (Array.isArray(allRecords) && allRecords.length > 0) {
          // 获取当前选择的月份
          const targetMonth = currentMonth || new Date();
          const targetYear = targetMonth.getFullYear();
          const targetMonthNum = targetMonth.getMonth();
          console.log('目标月份:', targetYear, '年', targetMonthNum + 1, '月');
          
          // 筛选出当前月份的数据
          const monthRecords = allRecords.filter(item => {
            if (item && item.uploadTime) {
              const date = new Date(item.uploadTime);
              return date.getFullYear() === targetYear && date.getMonth() === targetMonthNum;
            }
            return false;
          });
          
          console.log(`匹配到 ${targetYear}年${targetMonthNum + 1}月 的步数记录数:`, monthRecords.length);
          
          // 调试：打印完整的记录对象
          if (allRecords.length > 0) {
            console.log('步数记录示例（完整对象）:');
            console.log('第1条记录:', JSON.stringify(allRecords[0]));
            console.log('第1条记录所有字段:', Object.keys(allRecords[0]));
          }
          
          if (monthRecords.length > 0) {
            // 按日期分组，每天取最新的一条数据
            const dailyData = {};
            monthRecords.forEach(item => {
              if (item && item.uploadTime && item.steps) {
                const date = new Date(item.uploadTime).getDate(); // 获取日期（1-31）
                if (!dailyData[date] || item.uploadTime > dailyData[date].uploadTime) {
                  dailyData[date] = item;
                }
              }
            });
            
            // 获取当月的天数
            const daysInMonth = new Date(targetYear, targetMonthNum + 1, 0).getDate();
            
            // 生成完整的日期序列（1-当月天数）
            const dates = Array.from({ length: daysInMonth }, (_, i) => i + 1);
            
            chartData.categories = dates.map(day => `${day}日`);
            chartData.series[0].data = dates.map(day => 
              dailyData[day] ? dailyData[day].steps : null
            );
            
            console.log('月步数图表数据已设置, categories:', chartData.categories.length, 'data:', chartData.series[0].data.filter(v => v !== null).length);
          }
        } else {
          console.warn('月步数图表无数据');
        }
      }
      
      console.log('最终图表数据:', chartData);
      this.setData({ chartData });
      
    } catch (error) {
      console.error('加载图表数据失败:', error);
      wx.showToast({
        title: '加载图表数据失败',
        icon: 'none'
      });
    }
  },
  
  // 获取用户信息
  async getUserInfo() {
    const openid = wx.getStorageSync('openid');
    const cachedPatientUid = wx.getStorageSync('patientUid');
    const phoneNumber = wx.getStorageSync('phoneNumber');
    
    let data = {};
    if (cachedPatientUid) {
      data = { patientUid: cachedPatientUid };
    } else if (phoneNumber) {
      data = { phoneNumber: phoneNumber };
    } else if (openid) {
      data = { wxUid: openid };
    } else {
      console.log('未找到登录信息，使用默认头像');
      return;
    }
    
    try {
      const res = await getPatientBaseObject(data);
      if (res && res.code === 0 && res.data && res.data.length > 0) {
        const user = res.data[0];
        const patientName = user.patientName || user.phoneNumber || '用户';
        const displayName = patientName.length > 1 
          ? patientName.charAt(0) + '*' 
          : patientName;
        
        this.setData({
          userInfo: {
            avatarUrl: user.avatarUrl || '/asserts/images/avatar_placeholder.jpg',
            displayName: displayName,
            patientName: patientName,
            patientUid: user.patientUid
          }
        });
        if (user.patientUid) {
          wx.setStorageSync('patientUid', user.patientUid);
        }
      }
    } catch (err) {
      console.error('获取用户信息失败:', err);
    }
  },

  onBack() { wx.navigateBack({ delta: 1 }); },
  onTimeTypeChange(e) {
    const type = e.currentTarget.dataset.type;
    let sectionTitle = '本周步数基本情况'; // 默认标题
    
    if (type === 'day') {
      sectionTitle = '今日步数基本情况';
    } else if (type === 'week') {
      sectionTitle = '本周步数基本情况';
    } else if (type === 'month') {
      sectionTitle = '本月步数基本情况';
    }
    
    this.setData({ chartTimeType: type, sectionTitle: sectionTitle }, () => {
      if (type === 'day') {
        // 切换到"日"时，将显示为具体日期
        const display = this.formatDateDisplay(this.data.currentDate);
        const ymd = this.formatDateYMD(this.data.currentDate);
        this.setData({ chartDateRange: display, selectedDate: ymd });
      } else if (type === 'week') {
        const { start, end } = this.getWeekRange(this.data.currentDate);
        this.setData({
          weekStartDate: start,
          weekEndDate: end,
          chartDateRange: this.formatDateRangeDisplay(start, end)
        });
      } else if (type === 'month') {
        // 切换到月视图时，显示当前月份
        const monthDisplay = this.formatMonthDisplay(this.data.currentMonth);
        this.setData({
          chartDateRange: monthDisplay
        });
      }
      this.updateChartData();
    });
  },
  onTimeChange(e) {
    const type = e.detail.type;
    this.setData({ chartTimeType: type });
    // 根据时间类型更新数据
    this.updateChartData();
  },
  onOpenCalendar() {
    const { chartTimeType } = this.data;
    console.log('点击日期选择器，当前时间类型:', chartTimeType);
    
    // 更新日历日期范围（最近三个月）
    const maxDate = new Date();
    const minDate = new Date();
    minDate.setMonth(minDate.getMonth() - 3);
    
    // 日/月使用单选，周使用范围选择
    this.setData({
      calendarType: chartTimeType === 'week' ? 'range' : 'single',
      calendarMinDate: minDate.getTime(),
      calendarMaxDate: maxDate.getTime(),
      showCalendar: true
    });
  },

  // 打开月份选择器
  openMonthPicker() {
    console.log('openMonthPicker 被调用');
    const today = new Date();
    
    // 生成月份选项列表（最近6个月，符合ActionSheet限制）
    const monthOptions = [];
    const monthDates = [];
    
    for (let i = 5; i >= 0; i--) {
      const date = new Date(today.getFullYear(), today.getMonth() - i, 1);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      monthOptions.push(`${year}年${month}月`);
      monthDates.push(date);
    }
    
    console.log('月份选项:', monthOptions);
    
    wx.showActionSheet({
      itemList: monthOptions,
      success: (res) => {
        console.log('选择了月份，索引:', res.tapIndex);
        if (res.tapIndex >= 0) {
          const selectedDate = monthDates[res.tapIndex];
          const monthDisplay = this.formatMonthDisplay(selectedDate);
          
          console.log('选择的月份:', monthDisplay);
          
          this.setData({
            currentMonth: selectedDate,
            chartDateRange: monthDisplay
          }, () => {
            this.updateChartData();
          });
        }
      },
      fail: (err) => {
        console.error('月份选择器失败:', err);
      }
    });
  },
  onCalendarClose() {
    this.setData({ showCalendar: false });
  },
  onCalendarConfirm(e) {
    const { chartTimeType } = this.data;
    if (chartTimeType === 'day') {
      const date = new Date(e.detail);
      this.setData({
        currentDate: date,
        selectedDate: this.formatDateYMD(date),
        chartDateRange: this.formatDateDisplay(date),
        showCalendar: false
      }, () => this.updateChartData());
    } else if (chartTimeType === 'week') {
      const [startTs, endTs] = e.detail;
      const start = new Date(startTs);
      const end = new Date(endTs);
      this.setData({
        weekStartDate: start,
        weekEndDate: end,
        currentDate: start,
        chartDateRange: this.formatDateRangeDisplay(start, end),
        showCalendar: false
      }, () => this.updateChartData());
    } else if (chartTimeType === 'month') {
      // 月视图：选择的日期用于确定月份
      const date = new Date(e.detail);
      const monthDisplay = this.formatMonthDisplay(date);
      this.setData({
        currentMonth: date,
        chartDateRange: monthDisplay,
        showCalendar: false
      }, () => this.updateChartData());
    } else {
      this.setData({ showCalendar: false });
    }
  },

  onDatePicked(e) {
    // 仅在"日"模式下生效
    const value = e.detail.value; // YYYY-MM-DD
    const date = new Date(value.replace(/-/g, '/'));
    this.setData({
      selectedDate: value,
      currentDate: date,
      chartDateRange: this.formatDateDisplay(date)
    }, () => {
      this.updateChartData();
    });
  },
  onPrevDate() {
    if (this.data.chartTimeType === 'day') {
      const prev = this.shiftDay(this.data.currentDate, -1);
      this.setData({
        currentDate: prev,
        selectedDate: this.formatDateYMD(prev),
        chartDateRange: this.formatDateDisplay(prev)
      }, () => this.updateChartData());
    } else if (this.data.chartTimeType === 'week') {
      const start = this.shiftDay(this.data.weekStartDate || this.data.currentDate, -7);
      const end = this.shiftDay(this.data.weekEndDate || this.data.currentDate, -7);
      this.setData({
        weekStartDate: start,
        weekEndDate: end,
        currentDate: start,
        chartDateRange: this.formatDateRangeDisplay(start, end)
      }, () => this.updateChartData());
    } else if (this.data.chartTimeType === 'month') {
      // 月视图：向前一个月（无限制）
      const prevMonth = new Date(this.data.currentMonth);
      prevMonth.setMonth(prevMonth.getMonth() - 1);
      const monthDisplay = this.formatMonthDisplay(prevMonth);
      const yearMonth = `${prevMonth.getFullYear()}年${prevMonth.getMonth() + 1}月`;
      this.setData({
        currentMonth: prevMonth,
        chartDateRange: monthDisplay
      }, () => this.updateChartData());
      console.log('切换到上个月:', yearMonth);
    } else {
      this.updateChartData();
    }
  },
  onNextDate() {
    if (this.data.chartTimeType === 'day') {
      const next = this.shiftDay(this.data.currentDate, 1);
      this.setData({
        currentDate: next,
        selectedDate: this.formatDateYMD(next),
        chartDateRange: this.formatDateDisplay(next)
      }, () => this.updateChartData());
    } else if (this.data.chartTimeType === 'week') {
      const start = this.shiftDay(this.data.weekStartDate || this.data.currentDate, 7);
      const end = this.shiftDay(this.data.weekEndDate || this.data.currentDate, 7);
      this.setData({
        weekStartDate: start,
        weekEndDate: end,
        currentDate: start,
        chartDateRange: this.formatDateRangeDisplay(start, end)
      }, () => this.updateChartData());
    } else if (this.data.chartTimeType === 'month') {
      // 月视图：向后一个月（无限制）
      const nextMonth = new Date(this.data.currentMonth);
      nextMonth.setMonth(nextMonth.getMonth() + 1);
      const monthDisplay = this.formatMonthDisplay(nextMonth);
      const yearMonth = `${nextMonth.getFullYear()}年${nextMonth.getMonth() + 1}月`;
      this.setData({
        currentMonth: nextMonth,
        chartDateRange: monthDisplay
      }, () => this.updateChartData());
      console.log('切换到下个月:', yearMonth);
    } else {
      this.updateChartData();
    }
  },
  async updateChartData() {
    // 同时更新统计数据和图表数据
    await this.loadStatistics();
    await this.loadChartData();
  },

  // 工具：日期格式化
  formatDateYMD(date) {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
  },
  formatDateDisplay(date) {
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${m}月${d}日`;
  },
  formatDateRangeDisplay(start, end) {
    const sm = String(start.getMonth() + 1).padStart(2, '0');
    const sd = String(start.getDate()).padStart(2, '0');
    const em = String(end.getMonth() + 1).padStart(2, '0');
    const ed = String(end.getDate()).padStart(2, '0');
    return `${sm}月${sd}日-${em}月${ed}日`;
  },
  formatMonthDisplay(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const currentYear = new Date().getFullYear();
    
    // 如果是当前年份，只显示月份；否则显示年月
    if (year === currentYear) {
      return `${month}月`;
    } else {
      return `${year}年${month}月`;
    }
  },
  shiftDay(date, delta) {
    const d = new Date(date.getTime());
    d.setDate(d.getDate() + delta);
    return d;
  },
  getWeekRange(date) {
    const d = new Date(date.getTime());
    const weekday = d.getDay(); // 0 Sun..6 Sat
    const mondayOffset = weekday === 0 ? -6 : 1 - weekday;
    const start = this.shiftDay(d, mondayOffset);
    const end = this.shiftDay(start, 6);
    return { start, end };
  },
  // 生成单日图表数据（兼容旧代码，实际已由API调用替代）
  generateDayChartData() {
    return { categories: [], series: [{ name: '步数', data: [], color: '#52C41A', type: 'bar' }] };
  },

  // 生成周图数据（兼容旧代码，实际已由API调用替代）
  generateWeekChartData() {
    return { categories: [], series: [{ name: '步数', data: [], color: '#52C41A', type: 'bar' }] };
  },

  // 生成月图数据（兼容旧代码，实际已由API调用替代）
  generateMonthChartData() {
    return { categories: [], series: [{ name: '步数', data: [], color: '#52C41A', type: 'bar' }] };
  },

  // 计算目标进度和相关数据
  calculateGoalProgress() {
    const { currentSteps, goalSteps } = this.data;
    
    // 计算进度百分比
    const percent = goalSteps > 0 ? Math.min((currentSteps / goalSteps) * 100, 100) : 0;
    
    // 计算剩余步数
    const remaining = Math.max(goalSteps - currentSteps, 0);
    
    // 计算消耗卡路里（约每1000步消耗35卡路里）
    const calories = Math.round((currentSteps / 1000) * 35);
    
    // 计算距离（约每步0.7米）
    const distanceMeters = currentSteps * 0.7;
    const distance = (distanceMeters / 1000).toFixed(2);
    
    // 计算相当于几个鸡蛋（约40卡路里/个）
    const eggs = calories > 0 ? Math.ceil(calories / 40) : 0;
    
    // 计算相当于几圈操场（400米跑道，1圈=0.4km）
    const laps = (parseFloat(distance) * 2.5).toFixed(2);
    
    this.setData({
      progressPercent: percent.toFixed(2),
      remainingSteps: remaining,
      caloriesBurned: calories,
      distanceKm: distance,
      eggsCount: eggs,
      lapsCount: laps
    });
  },

  // 修改目标步数
  onEditGoal() {
    wx.showModal({
      title: '修改目标',
      content: '请输入目标步数',
      editable: true,
      placeholderText: String(this.data.goalSteps),
      success: (res) => {
        if (res.confirm && res.content) {
          const newGoal = parseInt(res.content);
          if (newGoal > 0 && !isNaN(newGoal)) {
            this.setData({
              goalSteps: newGoal
            }, () => {
              this.calculateGoalProgress();
              wx.showToast({
                title: '目标已更新',
                icon: 'success'
              });
            });
          } else {
            wx.showToast({
              title: '请输入有效数字',
              icon: 'none'
            });
          }
        }
      }
    });
  }
});
